package com.pic4493.utils;

import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import com.pic4493.comm.Session;
import com.pic4493.entities.DJson;
import com.pic4493.entities.EQQToken;
import com.pic4493.entities.EUser;
import com.pic4493.net.NetClientJ;
import com.tencent.connect.UserInfo;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

/**
 * 用于使用QQ互联授权，登录的辅助类
 * 
 * @author lichen
 * @since 2014-04-04
 */
public class UtiQQSDK
{
   public static final String APP_ID = "1101323870";// 222222
   public static final String SCOPE = "get_simple_userinfo";
   public Tencent mTencent;
   public Context mContext;
   public UserInfo userInfo;
   public EQQToken mToken;

   public UtiQQSDK(Context context)
   {
	  this.mContext = context;
	  mTencent = Tencent.createInstance(APP_ID, context);
   }

   /**
    * 登录
    * 
    * @since 2014-02-28
    */
   public void login()
   {
	  if (!mTencent.isSessionValid())
	  {
		 mTencent.login((Activity) mContext, SCOPE, new BaseUIListener()
		 {

			@Override
			protected void doComplete(JSONObject obj)
			{
			   try
			   {
				  mToken = new EQQToken();
				  mToken.setOpenid(obj.optString("openid"));
				  mToken.setAccess_token(obj.optString("access_token"));
				  mToken.setExpires_in(obj.optString("expires_in"));

				  UtiQQToken.writeAccessToken(mContext, mToken);
				  userInfo = new UserInfo(mContext, mTencent.getQQToken());
				  getUserInfo();
			   }
			   catch (Exception e)
			   {
				  Log.d("ERROR", "UtiQQSDK.login().new BaseUIListener() {...}_doComplete(obj) " + e);
			   }
			}
		 });
	  }
	  else
	  {
		 mTencent.logout(mContext);
	  }
   }

   /**
    * 获取用户信息
    * 
    * @author lichen
    * @since 2014-04-04
    */
   public void getUserInfo()
   {
	  userInfo.getUserInfo(new BaseUIListener()
	  {
		 @Override
		 protected void doComplete(JSONObject obj)
		 {
			try
			{
			   String headurl = obj.optString("figureurl_1");
			   String nickname = obj.optString("nickname");
			   new QQLoginTask().execute(new String[] { mToken.getOpenid(), headurl, nickname });
			}
			catch (Exception e)
			{
			   Log.d("ERROR", "UtiQQSDK.getUserInfo().new BaseUIListener() {...}_doComplete(obj) " + e);
			}
		 }
	  });
   }

   /**
    * 需要传入三个参数,openid,headurl,nickname
    * 
    * @author Administrator
    * 
    */
   class QQLoginTask extends AsyncTask<String, Void, DJson>
   {
	  @Override
	  protected void onPreExecute()
	  {
		 UtiDialog.getInstance().ShowLoadingDialogNoTitleEX(mContext, "加载数据中请稍候...");
	  }

	  @Override
	  protected DJson doInBackground(String... params)
	  {
		 return NetClientJ.QQLogin(params[0], params[1], params[2]);
	  }

	  @Override
	  protected void onPostExecute(DJson result)
	  {
		 UtiDialog.getInstance().DismissLoadingDialog();
		 try
		 {
			EUser user = new EUser();
			user.setNickName(result.getBody().optString("nickname"));
			user.setPassWord(result.getBody().optString("passwd"));
			user.setUserId(result.getBody().optString("uid"));
			user.setUserName(result.getBody().optString("username"));
			user.setNewsCount(result.getBody().optInt("msgCount"));
			user.setHeadImage(result.getBody().optString("avatars"));
			Session.getInstance().setUser(user);
			Activity act = (Activity) mContext;
			act.setResult(Activity.RESULT_OK);
			act.finish();
		 }
		 catch (Exception e)
		 {
			Log.d("ERROR", "UtiQQSDK.QQLoginTask_onPostExecute(result) " + e);
		 }

	  }
   }

   /**
    * 用户授权和获取用户信息的回调
    * 
    * @author lichen
    * @since 2014-04-04
    */
   public class BaseUIListener implements IUiListener
   {

	  @Override
	  public void onComplete(Object response)
	  {
		 doComplete((JSONObject) response);
	  }

	  protected void doComplete(JSONObject obj)
	  {

	  }

	  @Override
	  public void onError(UiError e)
	  {
		 Toast.makeText(mContext, e.errorMessage, Toast.LENGTH_SHORT).show();
	  }

	  @Override
	  public void onCancel()
	  {
		 Toast.makeText(mContext, "取消操作", Toast.LENGTH_SHORT).show();
	  }

   }

}
